#pragma once

#include <iostream>
#include "err.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
#include "Thread.hpp"
#include "RingQueue.hpp"
#include "LockGuard.hpp"

namespace ns_server
{
    static const uint16_t default_port = 8080;

    class UdpServer
    {
    public:
        UdpServer(uint16_t port = default_port) : _port(port)
        {
            pthread_mutex_init(&_mmtx, nullptr);

            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(1, std::bind(&UdpServer::BroadCast, this));
        }

        ~UdpServer()
        {
            pthread_mutex_destroy(&_mmtx);

            p->join();
            c->join();

            delete p;
            delete c;
        }

        void start()
        {
            // 1 创建socket接口，打开网络文件
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "create socket error" << std::endl;
                exit(SOCKED_ERR);
            }
            std::cout << "create socket success" << std::endl;

            // 2 给服务器指明IP地址和Port
            struct sockaddr_in local;
            memset(&local, sizeof(local), 0);

            local.sin_family = AF_INET;
            local.sin_port = htons(_port);      // host to network short
            local.sin_addr.s_addr = INADDR_ANY; // bind本主机任意ip
            if (bind(_sock, (sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error" << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success" << std::endl;

            c->run();
            p->run();
        }

        void addUser(std::string &name, sockaddr_in &peer)
        {
            LockGuard lg(&_mmtx);
            _users[name] = peer;
        }

        void Recv()
        {
            char buffer[1024];
            // 网络服务都是循环！
            while (true)
            {
                // recv里有两个输出型参数
                sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
                if (n > 0)
                {
                    buffer[n] = 0;
                }
                else
                {
                    continue;
                }

                // 发消息人的ip和port
                std::string client_ip = inet_ntoa(peer.sin_addr); // net->ascii
                uint16_t client_port = ntohs(peer.sin_port);

                // 构造了发消息人的姓名
                std::string name = client_ip + "-" + to_string(client_port);

                addUser(name, peer);
                rq.push(name + buffer);
            }
        }

        void BroadCast()
        {
            while (true)
            {
                std::string send_string;
                rq.pop(&send_string);

                std::vector<sockaddr_in> v; // 临时数组，存放要发给那些人

                {
                    LockGuard lg(&_mmtx);
                    for (auto user : _users)
                    {
                        v.push_back(user.second);
                    }
                }

                for (auto user : v)
                {
                    sendto(_sock, send_string.c_str(), send_string.size(), 0, (sockaddr *)&user, sizeof(user));
                }
            }
        }

    private:
        // 1. socket的id，相当于文件id
        int _sock;
        // 2. port
        uint16_t _port;

        // 3 一个线程负责收放消息；另一个线程负责发消息
        Thread *c; // 收消息
        Thread *p; // 发消息

        // 4 环形队列来实现生产消费
        RingQueue<std::string> rq;

        // 5 信息要群发给所有人，要记录所有人的ip和端口号
        std::unordered_map<std::string, sockaddr_in> _users;

        // 6 一把锁保证在读取要发送给哪些人时是安全的
        //  在读取_users时，另一个线程收到了消息，会修改这个map
        pthread_mutex_t _mmtx;
    };
}